<template>
  <div>
    <TopFilter :list="topFilterList" ref="top"
               :cols="3"
               @filterChange="changeHandle"
               @onCollapse="collapseHandle"
               :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading"
          tip="Loading...">
      <FilterTables ref="table"
                   columnsRef="orderImport"
                   :columns="columns"
                   :fetchapi="fetchApi"
                   :params="fetchParams"
                   :datakey="'records'"
                   :onSyncTableData="tableChange"
                   :isSelectColumn="false"
                   :onColumnsChange="(columns) => (this.columns = columns)">
        <template slot="controls"
                  slot-scope="props">
          <multiuse-button size="small"
                           type="primary"
                           @click="addHandle(1)">订单导入
          </multiuse-button>
          <multiuse-button size="small"
                           type="primary"
                           @click="addHandle(2)">导 出
          </multiuse-button>
        </template>
      </FilterTables>
    </Spin>

    <BaseDialog :visible.sync="isImport" :title="'订单导入'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <importFiles @close="importcloseHandler" />
    </BaseDialog>

    <Drawer :visible.sync="addVisible"
            :title="'订单信息'"
            destroyOnClose
            :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
            width="80%">
      <addModel :rowData="formData"
                @close="addCloseHandler"/>
    </Drawer>
    <Drawer :visible.sync="detailVisible"
            :title="'订单信息'"
            destroyOnClose
            :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
            width="80%">
      <detailModel :rowData="formData"
                   @close="detailCloseHandler"/>
    </Drawer>
  </div>
</template>
<script>
import {dictionary} from '@/utils/dictMixin';
import {region} from '@/api/cms-common/region';
import { getSaleAreaInfo } from '@/api/cms-common/dealerdata/index';
import {deleteOrderById, exportList, getList} from '@/api/omSaleP/OrderManagement/OrderImport/index.js';
import importFiles from './importFiles';
import addModel from './addModel';
import detailModel from './detailModel';
import {exportExcelFile} from '@/utils';

export default {
  name: 'orderImport',
  mixins: [dictionary,region],
  components: {
    addModel,
    detailModel,
    importFiles
  },
  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: getList,
      fetchParams: {
        searchType: 1, //查询类型 1为提报查询 2为审核查询列表 3为订货单主机厂查询 4为订货单经销商查询
        saveType: 'OEM', //DLR为经销商查询 OEM为厂端查询
        majorType: 1 //是否大客户 1为非大客户查询 2为大客户查询 3为全部查询
      },
      tableList: [],
      formData: {},
      exportLoading: false,
      addVisible: false,
      detailVisible: false,
      isImport: false,
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.initProvince();
    this.getSaleAreaInfo();
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '所属区域',
          fieldName: 'areaId',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '省份',
          fieldName: 'provinceId',
          placeholder: '请选择',
          itemList: [],
          change: (value) => {
            this.initCity(value);
          },
        },
        {
          type: 'SELECT',
          label: '城市',
          fieldName: 'cityId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '输入多个经销商代码时，请用英文逗号隔开',
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'startDate|endDate',
          placeholder: '请选择',
          initialValue: [],
          dateType: 'exactdaterange',
        },
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          placeholder: '请选择',
          dateType: 'month'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 160,
          fixed: 'left',
          render: (props, h) => {
            return (
                <div>
                  <multiuse-button size="mini" type="text" disabled={(props.row.orderStatus !== 21041001)}
                                   onClick={() => this.editHandle(props.row, 1)}>
                    编辑
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" onClick={() => this.editHandle(props.row, 2)}>
                    详情
                  </multiuse-button>
                  <el-divider direction="vertical"/>
                  <multiuse-button size="mini" type="text" disabled={(props.row.orderStatus !== 21041001)}
                                   onClick={() => this.editHandle(props.row, 3)}>
                    删除
                  </multiuse-button>
                </div>
            );
          },
        },
        {
          title: '所属区域',
          dataIndex: 'areaName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '订单编号',
          dataIndex: 'orderNo',
          sorter: true,
          filter: true,
          filterType: 'input',
          align: 'center',
          width: 200,
        },
        {
          title: '订单类型',
          dataIndex: 'orderType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2105'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderType, '2105')}</span>;
          },
        },
        {
          title: '订单细分类型',
          dataIndex: 'orderDetailName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单状态',
          dataIndex: 'orderStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2104'),
          render: (p) => {
            return <span>{this.createDictText(p.row.orderStatus, '2104')}</span>;
          },
        },
        {
          title: '订单年月',
          dataIndex: 'orderYearMonth',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '订单紧急度',
          dataIndex: 'emergencyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2101'),
          render: (p) => {
            return <span>{this.createDictText(p.row.emergencyType, '2101')}</span>;
          },
        },
        {
          title: '运输方式',
          dataIndex: 'transportType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2409'),
          render: (p) => {
            return <span>{this.createDictText(p.row.transportType, '2409')}</span>;
          },
        },
        {
          title: '收车地址',
          dataIndex: 'orderAddress',
          width: 400,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送达城市',
          dataIndex: 'orderCity',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '联系方式',
          dataIndex: 'linkPhone',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '创建人',
          dataIndex: 'createdName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '创建日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        }
      ];
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    tableChange(val) {
      val.map((x) => {
      });
    },
    async getSaleAreaInfo() {
      const res = await getSaleAreaInfo(15061015);
      if (res.resultCode === 200) {
        this.areaList = res.data;
        res.data.map((x) => {
          this.topFilterList.find((item) => item.fieldName === 'areaId').itemList.push({ text: x.orgName, value: x.id });
        });
      }
    },
    //初始化所在省份
    async initProvince() {
      this.topFilterList.find((item) => item.fieldName === 'provinceId').itemList = this.createRegionList();
    },
    //初始化所在市数据
    async initCity(provinceId) {
      //清空市
      this.topFilterList.find((item) => item.fieldName === 'cityId').itemList = [];
      this.topFilterList.find((item) => item.fieldName === 'cityId').initialValue = '';
      if (!provinceId || typeof provinceId == 'undefined') {
        return;
      }
      //取省数据
      let rd = this.getRegionData();
      this.cityData = rd[provinceId].children;
      this.topFilterList.find((item) => item.fieldName === 'cityId').itemList = this.createSubRegionList(this.cityData);
    },
    async addHandle(type) {
      if (type === 1) {
        // 导入
        this.isImport = true;
      } else {
        // 导出
        this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.top.SUBMIT_FORM();
          this.exportLoading = true;
          exportList(this.fetchParams).then(response => {
            exportExcelFile(response.data, '总部订单导入');
            this.exportLoading = false;
          }).catch(err => {
            console.log(err);
          });
        }).catch((err) => {
          console.log(err);
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      }
    },
    // 导入完成回调方法
    importcloseHandler() {
      this.isImport = false;
      this.fetchParams = Object.assign({}, this.fetchParams);
    },
    async editHandle(data, type) {
      if (type === 1) {
        // 编辑
        if (data.orderStatus !== 21041001) {
          this.$notify({
            title: '提示',
            message: '新建状态的订单才允许修改',
            type: 'warning',
          });
          return;
        }
        this.formData = data;
        this.addVisible = true;
      } else if (type === 2) {
        // 详情
        this.formData = data;
        this.detailVisible = true;
      } else {
        // 删除
        if (data.orderStatus !== 21041001) {
          this.$notify({
            title: '提示',
            message: '新建状态的订单才允许删除',
            type: 'warning',
          });
          return;
        }
        await this.$confirm('是否确定取消?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
            .then(async () => {
              let res = await deleteOrderById({orderId: data.orderId});
              if (res.resultCode === 200) {
                this.$notify({
                  title: '成功',
                  message: '取消成功',
                  type: 'success',
                });
                this.fetchParams = Object.assign({}, this.fetchParams);
              }
            }).catch(() => {
            });
      }
    },
    addCloseHandler(val) {
      this.addVisible = false;
      if (val) {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    detailCloseHandler() {
      this.detailVisible = false;
    }
  }
};
</script>
